package com.ztstkj.lzscale.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import androidx.activity.enableEdgeToEdge
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.proembed.service.MyService
import com.sscl.baselibrary.utils.DebugUtil
import com.ztstkj.lzscale.R
import com.ztstkj.lzscale.databinding.ActivitySplashBinding
import com.ztstkj.lzservices.dto.EquipmentOutput
import com.ztstkj.lzservices.exceptions.ApiException
import com.ztstkj.lzservices.exceptions.LogConstant
import com.ztstkj.lzservices.exceptions.apiCall
import com.ztstkj.lzservices.extension.ExceptionExt.toStackTraceString
import com.ztstkj.lzservices.extension.ViewExtension.setOnClickListenerAfterMultipleClicks
import com.ztstkj.lzservices.mmkvs.MmkvManager
import com.ztstkj.lzservices.model.SysSetting
import com.ztstkj.lzservices.model.SysTypeEnum
import com.ztstkj.lzservices.networks.NetworkUtils
import com.ztstkj.lzservices.retrofits.Api
import com.ztstkj.lzservices.utils.SpeakUtil
import kotlinx.coroutines.launch

@SuppressLint("CustomSplashScreen")
class SplashActivity : BaseActivity() {
    private lateinit var countDownTimer: CountDownTimer
    private lateinit var binding: ActivitySplashBinding
    private var timeLeftInMillis: Long = 5000
    private var currentEquipment: EquipmentOutput? = null
    private var currentSet: SysSetting? = null
    private var speechCount: Int=0
    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_splash)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_splash)
        binding.tvAndroidID.text = "No:${DeviceUtils.getAndroidID()}  V${AppUtils.getAppVersionName()}"
        bindRootClick()
        //startCountdown()
        //1. 先判断设备有没有激活，无论有没有网路，只要激活直接进入主页面
        val isActivate=isActivate()
        if(isActivate){
            loadUserCard()
            redirectToMain()
        }
    }

    private fun bindRootClick() {
        binding.root.setOnClickListener {
            redirectTo()
        }
        binding.tvAndroidID.setOnClickListenerAfterMultipleClicks{
            val mXService = MyService(baseContext)
            mXService.hideNavBar = !mXService.hideNavBar
        }
    }

    private fun startCountdown() {
        countDownTimer = object : CountDownTimer(timeLeftInMillis, 1000) {
            @SuppressLint("SetTextI18n")
            override fun onTick(millisUntilFinished: Long) {
                runOnUiThread {
                    binding.tvCountdown.text = (millisUntilFinished / 1000).toString() + " s"
                }
                if(currentEquipment!=null){
                    redirectTo()
                }
            }
            override fun onFinish() {
                runOnUiThread {binding.tvCountdown.text = "0 s"}
                redirectTo()
            }
        }
        countDownTimer.start()
    }
    private fun redirectToMain(){
        currentSet = MmkvManager.getSysSetting()
        if (currentSet?.sysType == SysTypeEnum.COLLECT.value) {
            startActivity(Intent(applicationContext, MainActivity::class.java))
            finish()
        } else {
            startActivity(Intent(applicationContext, RecyclableActivity::class.java))
            finish()
        }
    }

    private fun redirectTo() {
        if (currentEquipment != null) {
            countDownTimer.cancel()
            currentSet = MmkvManager.getSysSetting()
            if (currentSet?.sysType == SysTypeEnum.COLLECT.value) {
                startActivity(Intent(applicationContext, MainActivity::class.java))
                finish()
            } else {
                startActivity(Intent(applicationContext, RecyclableActivity::class.java))
                finish()
            }
        } else {
            startCountdown()
            MmkvManager.addLog(LogConstant.APPDOWN, "设备信息加载失败")
        }
    }

    private fun isActivate():Boolean {
        try {
            currentEquipment=MmkvManager.getEquipment()
            if(currentEquipment!=null){
                if(NetworkUtils.onLine){
                    //有网络更新设备信息
                    updateEquipment()
                }
                return true
            }
            DebugUtil.debugOut("splash","缓存没有设备信息")
            updateEquipment()
            if(currentEquipment!=null){
                DebugUtil.debugOut("splash","缓存没有设备信息，读取服务器后有了")
                return true
            }
            DebugUtil.debugOut("splash","缓存没有设备信息，读取服务器后也没有")

        } catch (e: Exception) {
            e.printStackTrace()
            SpeakUtil.speech(this@SplashActivity, "设备异常")
            MmkvManager.addLog(LogConstant.BUSINESS, e.toStackTraceString())
        }
        return false
    }
    private fun updateEquipment(){
        lifecycleScope.launch {
            val resp = apiCall { Api.get().getEquipment(DeviceUtils.getAndroidID()) }
            if (resp.code == 200 && resp.data != null) {
                currentEquipment = resp.data
                MmkvManager.setEquipment(resp.data)
                ToastUtils.showLong("设备加载成功", 2000)
            } else if(resp.code==500){
                countDownTimer.cancel()
                val statusTxt="当前设备没有激活"
                SpeakUtil.speech(this@SplashActivity, statusTxt)
                binding.tvAndroidStatus.text=statusTxt
                ToastUtils.showLong(statusTxt, 5000)
            }else if(resp.code==ApiException.CODE_NET_ERROR){
                if(speechCount<3){
                    SpeakUtil.speech(this@SplashActivity, "请检查网络")
                    speechCount++
                }else{
                    ToastUtils.showLong("请检查网络", 3000)
                }
                binding.tvAndroidStatus.text="没有网络"
            }
        }
    }

    private fun loadUserCard() {
        lifecycleScope.launch {
            DebugUtil.debugOut(tag, "开始${TimeUtils.getNowString()}")
            val resp = apiCall { Api.get().getCardQrcodeCount(currentEquipment?.deptId ?:0) }
            if (resp.success && resp.data != null) {
                val curCount = MmkvManager.getCardQrocodeCount()
                val serverCount = resp.data
                if (serverCount != curCount) {
                    val resp2 = apiCall { Api.get().getCardQrcodeList(currentEquipment?.deptId ?:0) }
                    if (resp2.success && resp2.data != null) {
                        val cardList = resp2.data
                        MmkvManager.setCardQrcodes(cardList)
                        MmkvManager.addLog(
                            LogConstant.CARD,
                            "updated，before:${curCount},after:${MmkvManager.getCardQrocodeCount()}"
                        )
                    }
                } else {
                    MmkvManager.addLog(
                        LogConstant.CARD,
                        "the latest，server：${serverCount} local：${curCount}"
                    )
                }
            }
        }
    }
}